package com.sanjiahantang.youjiarole.module.common.presenters;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListAdapter;

import com.sanjiahantang.plugin.roundimage.RoundedTransformationBuilder;
import com.sanjiahantang.plugin.swipemenulistview.SwipeMenu;
import com.sanjiahantang.plugin.swipemenulistview.SwipeMenuCreator;
import com.sanjiahantang.plugin.swipemenulistview.SwipeMenuItem;
import com.sanjiahantang.plugin.swipemenulistview.SwipeMenuListView;
import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.dialog.AlterGoodsNumDialog;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.TagGroup;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseBean;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.common.beans.CartGoodsBean;
import com.sanjiahantang.youjiarole.module.common.views.ShoppingCartView;
import com.sanjiahantang.youjiarole.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiarole.module.goods.models.IGoodsModel;
import com.sanjiahantang.youjiarole.module.goods.models.impl.GoodsModel;
import com.sanjiahantang.youjiarole.module.goods.views.impl.GoodsDetailActivity;
import com.sanjiahantang.youjiarole.module.me.favorite.views.impl.FavoriteActivity;
import com.sanjiahantang.youjiarole.module.me.order.views.impl.OrderActivity;
import com.sanjiahantang.youjiarole.utils.FileUtils;
import com.sanjiahantang.youjiarole.utils.SPUtils;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zy on 2017/9/5.
 */

public class ShoppingCartPresenter extends BaseMvpPresenter<ShoppingCartView> {
    private QuickAdapter<CartGoodsBean.Data> mCartGoodsAdapter;

    private Transformation mTransformation;
    //所有的商品集合
    private List<CartGoodsBean.Data> allCartGoodsList;
    //已经选择的商品集合
    private List<CartGoodsBean.Data> selectCartGoodsList;
    //商品id与数量,传入确认订单页
    private String goodsIdNumber;
    //商品属性，传入确认订单页
    private String goodsAttStr;
    //商品唯一标识rec_id，删除商品
    private String goodsRecId;
    private boolean isClicked;
    private boolean isAllSelected;
    private boolean isSingle;
    private Map<Integer, Boolean> flags;


    private IGoodsModel goodsModel;
    private AlterGoodsCallBack alterGoodsCallBack;
    private GetGoodsCallBack getGoodsCallBack;
    private DeleteGoodsCallBack deleteGoodsCallBack;

    public ShoppingCartPresenter() {
        goodsModel = new GoodsModel();
    }

    private boolean flag = false;//用来区分是首次加载还是刷新的标识

    public void init() {
        selectCartGoodsList = new ArrayList<>();
        allCartGoodsList = new ArrayList<>();
        initTransformation();
    }

    public ListAdapter getAdapter(BaseMvpActivity context) {
        return mCartGoodsAdapter = new QuickAdapter<CartGoodsBean.Data>(context, R.layout.item_cart_goods) {
            @Override
            protected void convert(final BaseAdapterHelper helper, final CartGoodsBean.Data item) {
                helper.setText(R.id.goods_name, item.getGoodsName());
                helper.setText(R.id.goods_price, "¥" + item.getBasePrice().replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ","));
                TagGroup tagGroup = helper.getView(R.id.tagGroup);

                tagGroup.setTags(item.getMgpiValue());
                //加载网络图片
                Picasso.with(context).load(FileUtils.rePath(item.getUrl())).fit().transform(mTransformation)
                        .placeholder(RES_ID_GOODS_DEFAULT).into((ImageView) helper.getView(R.id.goods_image));

                final int goods_number = item.getNumber();
                final int rec_id = item.getMgsciId();
                String goods_price = item.getBasePrice();
                helper.setText(R.id.goods_number, goods_number + "");
                //计算金钱
                BigDecimal total_price = getTotalPrice(goods_number, goods_price);

                helper.setText(R.id.goods_total_price, total_price.toString());
                //修改商品数量
                alterGoodsNumber(context, helper, goods_number, rec_id, item.getStockCount());


                //选择商品
                CheckBox mCheckBoxSelect = (CheckBox) helper.getView().findViewById(R.id.select_goods);

                mCheckBoxSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        //Utils.showToast(getActivity(), item.getGoods_name() + isChecked);
                        int position = helper.getPosition();
                        if (isChecked && !selectCartGoodsList.contains(item)) {
                            selectCartGoodsList.add(item);
                            flags.put(position, true);
                            if (selectCartGoodsList.size() == allCartGoodsList.size()) {
                                isClicked = true;
                                isAllSelected = true;
                                mView.checkButton(true, true);

                            }
                        } else if (!isChecked && selectCartGoodsList.contains(item)) {
                            selectCartGoodsList.remove(item);
                            flags.put(position, false);
                            isClicked = false;
                            isAllSelected = false;
                            isSingle = true;
                            mView.checkButton(false, false);

                        } else if (isChecked && selectCartGoodsList.contains(item)) {
                            if (selectCartGoodsList.size() == allCartGoodsList.size()) {
                                isClicked = true;
                                isAllSelected = true;
                                mView.checkButton(true, true);
                            }
                        }

                        alterTotalPrice(selectCartGoodsList);
                    }
                });

                if (selectCartGoods(item)) mCheckBoxSelect.setChecked(true);
                else mCheckBoxSelect.setChecked(false);

                //跳转到商品详情页,点击图片以及商品名称
                helper.getView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toGoodsDetail(context, item);
                    }
                });

            }
        };
    }

    private void initTransformation() {
        mTransformation = new RoundedTransformationBuilder()
                .cornerRadiusDp(5)
                .borderColor(Color.TRANSPARENT)
                .borderWidthDp(1)
                .oval(false)
                .build();

    }

    //根据单价跟数量计算钱数
    private BigDecimal getTotalPrice(int goods_number, String goods_price) {
        BigDecimal one_price = new BigDecimal(goods_price);
        return one_price.multiply(new BigDecimal(goods_number));
    }

    //增加修改商品数量
    private void alterGoodsNumber(final Context context, BaseAdapterHelper helper, final int goods_number, final int rec_id, final int stockCount) {
        //减少商品
        helper.setOnClickListener(R.id.number_sub, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goods_number > 1) {
                    alterCartGoodsNumber(context, rec_id, goods_number - 1);
                }

            }
        });
        //增加商品
        helper.setOnClickListener(R.id.number_add, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goods_number < stockCount) {
                    alterCartGoodsNumber(context, rec_id, goods_number + 1);
                }

            }
        });
        //自定义商品数量

//        helper.setOnClickListener(R.id.goods_number, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //Utils.showToast(getActivity(), "自定义商品数量弹出框");
//                AlterGoodsNumDialog dialog = new AlterGoodsNumDialog(context, goods_number, new AlterGoodsNumDialog.OnAlertGoodsNumDialogListener() {
//                    @Override
//                    public void cancel() {
//                        //Toast.makeText(context, "取消", Toast.LENGTH_SHORT).show();
//                    }
//
//                    @Override
//                    public void confirm(String newNums) {
//                        // Toast.makeText(context, "确定" + newNums, Toast.LENGTH_SHORT).show();
//                        alterCartGoodsNumber(context, rec_id, Integer.parseInt(newNums));
//                    }
//                });
//                dialog.show();
//            }
//        });
    }

    private void alterCartGoodsNumber(Context context, int recId, int goodsNumber) {
        Map<String, Object> params = new HashMap<>();

        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(ShoppingCartView.KEY_GOODS_ID, recId);
        params.put(ShoppingCartView.KEY_NUMBER, goodsNumber);
        mView.showProgress();
        goodsModel.alterCartGoodsNumber(context, params, getAlterGoodsCallBack());
    }

    //修改结算合计金额与商品数量
    private void alterTotalPrice(List<CartGoodsBean.Data> selectCartGoodsList) {

        BigDecimal totalPrice = new BigDecimal(0.00);
        int totalNumber = 0;
        goodsIdNumber = "";
        goodsRecId = "";
        goodsAttStr = "";
        //获取商品id与数量传到确认订单页
        for (int i = 0; i < selectCartGoodsList.size(); i++) {
            totalNumber += selectCartGoodsList.get(i).getNumber();

            BigDecimal bigDecimal = getTotalPrice(selectCartGoodsList.get(i).getNumber(), selectCartGoodsList.get(i).getBasePrice());

            totalPrice = totalPrice.add(bigDecimal);
            goodsIdNumber += selectCartGoodsList.get(i).getMgsciId() + "-" + selectCartGoodsList.get(i).getNumber() + ",";

            goodsAttStr += String.valueOf(selectCartGoodsList.get(i).getMgiId()) + "-";

            goodsRecId += selectCartGoodsList.get(i).getSkuId() + ",";
        }
        //去掉最后一位逗号
        if (!TextUtils.isEmpty(goodsIdNumber) && goodsIdNumber != null)
            goodsIdNumber = goodsIdNumber.substring(0, goodsIdNumber.length() - 1);
        if (!TextUtils.isEmpty(goodsRecId) && goodsRecId != null)
            goodsRecId = goodsRecId.substring(0, goodsRecId.length() - 1);
        if (!TextUtils.isEmpty(goodsAttStr) && goodsAttStr != null)
            goodsAttStr = goodsAttStr.substring(0, goodsAttStr.length() - 1);

        mView.setPrice(totalPrice.toString(), totalNumber);

    }

    private boolean selectCartGoods(CartGoodsBean.Data item) {
        if (item == null) {
            return false;
        }
        for (CartGoodsBean.Data cartGoods : selectCartGoodsList) {
            if (cartGoods.getMgsciId() == item.getMgsciId()) {
                //当一个商品被选择，并且修改数量时，将已选集合中的更改数量之前的商品删除，添加新数据并重新计算价格
                selectCartGoodsList.remove(cartGoods);
                selectCartGoodsList.add(item);
                alterTotalPrice(selectCartGoodsList);
                return true;
            }
        }
        return false;
    }

    private void toGoodsDetail(Context context, CartGoodsBean.Data item) {
        Intent intent = new Intent(context, GoodsDetailActivity.class);
        intent.putExtra("goodsId", item.getMgiId());
        context.startActivity(intent);
    }

    public void reloadData(final BaseMvpActivity context) {
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(context)) {
            mView.switchLayout();
        } else {
            mView.hideNetError();
            ConfigValue.DATA_KEY = (String) SPUtils.get(context, SPConfig.KEY, "");
            if (ConfigValue.DATA_KEY != null && !ConfigValue.DATA_KEY.equals("")) {
                //本地存在key
            /*mFrameLayoutLogin.setVisibility(View.VISIBLE);
            pullRefreshLayout2.setVisibility(View.GONE);*/
                getCartGoodsData(context);


            } else {
                //不存在key，提示需要登录
                mView.showToLoginLayout();
                return;
            }
        }

        mView.hideCart();


        mCartGoodsAdapter.clear();
        mCartGoodsAdapter.addAll(allCartGoodsList);
        flags = new HashMap<>();
        for (int i = 0; i < allCartGoodsList.size(); i++) {
            flags.put(i, false);
        }
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(context);
                deleteItem.setBackground(new ColorDrawable(Color.RED));
                deleteItem.setWidth(Utils.dip2px(context, 60));
                deleteItem.setTitle("删除");
                deleteItem.setTitleColor(Color.WHITE);
                deleteItem.setTitleSize(16);
                menu.addMenuItem(deleteItem);
            }
        };

        mView.initMListView(creator, new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                //index的值就是在SwipeMenu依次添加SwipeMenuItem顺序值，类似数组的下标。
                //从0开始，依次是：0、1、2、3...
                switch (index) {
//                    case 0:
//                        Toast.makeText(context, "打开:"+position,Toast.LENGTH_SHORT).show();
//                        break;

                    case 0:
                        deleteGoods(context, allCartGoodsList.get(position).getMgsciId());
                        break;
                }

                // false : 当用户触发其他地方的屏幕时候，自动收起菜单。
                // true : 不改变已经打开菜单的样式，保持原样不收起。
                return false;
            }
        });


//        final ListViewSwipeGesture touchListener = new ListViewSwipeGesture(mListView, swipeListener, getActivity());
//        touchListener.SwipeType	=	ListViewSwipeGesture.Double;    //设置两个选项列表项的背景
//        mListView.setOnTouchListener(touchListener);
    }

    private void getCartGoodsData(Context context) {
        if (flag) {
            mView.showProgress();
            flag = false;
        }
        Map<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        goodsModel.getCartGoodsData(context, params, getGetGoodsCallBack());
    }

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (selectCartGoodsList == null || allCartGoodsList == null) {
            return;
        }
        if (isChecked) {
            isClicked = true;
            isAllSelected = true;
            //Utils.showToast(getActivity(), "全选");
            selectCartGoodsList.clear();
            selectCartGoodsList.addAll(allCartGoodsList);

        } else {
            isClicked = false;
            isAllSelected = false;
            // Utils.showToast(getActivity(), "全不选");
            if (selectCartGoodsList.size() == allCartGoodsList.size()) {
                selectCartGoodsList.clear();
            }
        }
        mCartGoodsAdapter.notifyDataSetChanged();
        alterTotalPrice(selectCartGoodsList);
        switch (buttonView.getId()) {
            case R.id.select_all:
                if (isChecked) {
                    mView.checkButton(null, true);
                } else {
                    mView.checkButton(null, false);
                }
                break;
            case R.id.select_all_delete:
                if (isChecked) {
                    mView.checkButton(true, null);
                } else {
                    mView.checkButton(false, null);
                }
                break;
        }
    }

    /**
     * 暂时根据请求获得的商品计算数量在购物车角标显示
     */
    private String getCartGoodsNums() {
        int nums = 0;
        for (CartGoodsBean.Data cartGoods : allCartGoodsList)
            nums += cartGoods.getNumber();
        return String.valueOf(nums);
    }


    private AlterGoodsCallBack getAlterGoodsCallBack() {
        if (alterGoodsCallBack == null) {
            alterGoodsCallBack = new AlterGoodsCallBack();
        }
        return alterGoodsCallBack;
    }

    private GetGoodsCallBack getGetGoodsCallBack() {
        if (getGoodsCallBack == null) {
            getGoodsCallBack = new GetGoodsCallBack();
        }
        return getGoodsCallBack;
    }

    private DeleteGoodsCallBack getDeleteGoodsCallBack() {
        if (deleteGoodsCallBack == null) {
            deleteGoodsCallBack = new DeleteGoodsCallBack();
        }
        return deleteGoodsCallBack;
    }

    public void toLogin(BaseMvpActivity context) {
        LoginActivity.logout(context);
    }

    public void goPageFavorite(BaseMvpActivity context) {
        //获取关注商品列表
        String key = (String) SPUtils.get(context, "key", "");
        if (!TextUtils.isEmpty(key)) {
            // Utils.showToast(getActivity(), "看看关注");
            goPageSimply(context, FavoriteActivity.class);
        } else {
            LoginActivity.logout(context);
        }
    }

    public void goPageCreateOrder(BaseMvpActivity context) {
        if (!TextUtils.isEmpty(goodsIdNumber)) {
            ConfigValue.selectGoodsList = selectCartGoodsList;
            Intent intent = new Intent(context, OrderActivity.class);
            intent.putExtra(KEY_TYPE, ORDER_TYPE_CART);
            Bundle b = new Bundle();
            b.putSerializable("cart", (ArrayList<CartGoodsBean.Data>) selectCartGoodsList);
            intent.putExtra(KEY_PARAM, b);
            context.startActivity(intent);
        }
    }

    public void deleteGoods(final BaseMvpActivity context, final int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("确认要删除所选商品吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteCartGoods(context, id);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }

    private void deleteCartGoods(Context context, int id) {
        mView.showProgress();
        Map<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put("mgsciId", id);
        goodsModel.deleteCartGoods(context, params, getDeleteGoodsCallBack());
    }

    private class AlterGoodsCallBack implements CallBack<BaseBean> {

        @Override
        public void onSuccess(BaseBean response, Context context, Object tag) {
            hideProgress();
            if (response.getCode() == RESPONSE_CODE_SUC) {
                // Utils.showToast(getActivity(), baseModel.getMessage());

                getCartGoodsData(context);
            } else

                Utils.showToast(context, response.getMessage());
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }

    private class GetGoodsCallBack implements CallBack<CartGoodsBean> {

        @Override
        public void onSuccess(CartGoodsBean response, Context context, Object tag) {
            hideProgress();
            Log.d("order", "getCartGoodsList");
            //已登录并且购物车为空
            if (response.getCode() == RESPONSE_CODE_SUC) {
                if (response.getData() == null || response.getData().size() == 0) {
                    //隐藏商品列表布局与登录按钮，显示空商品布局
                    mView.showEmptyCart();
                    allCartGoodsList.clear();
                } else {

                    //显示商品列表，隐藏空商品布局
                    mView.showCart();


                    //每次刷新查询购物车商品时都将全部商品集合清空重新赋值
                    allCartGoodsList.clear();
                    selectCartGoodsList.clear();
                    allCartGoodsList.addAll(response.getData());
                    if (isClicked) {
                        selectCartGoodsList.addAll(allCartGoodsList);
                        mCartGoodsAdapter.notifyDataSetChanged();
                        alterTotalPrice(selectCartGoodsList);
                    }

                    mCartGoodsAdapter.clear();
                    mCartGoodsAdapter.addAll(allCartGoodsList);
                    flags = new HashMap<>();
                    for (int i = 0; i < allCartGoodsList.size(); i++) {
                        flags.put(i, false);
                    }

                }


//            mPersonalView.setCartGoodsNums(getCartGoodsNums());
                Intent mIntent = new Intent(ConfigValue.ACTION_ALTER_CARTGOODS_NUMS);
                mIntent.putExtra("cartgoodsnum", getCartGoodsNums());
                //发送广播
                context.sendBroadcast(mIntent);

                Log.d("cart", response.getData().toString() + "/" + response.getMessage() + "/" + response.getCode());
            } else {

            }

        }

        @Override
        public void onFailure(String message) {
            mView.hideProgress();
        }
    }

    private void hideProgress() {
        if (mView != null) {
            mView.hideProgress();
        }

    }

    private class DeleteGoodsCallBack implements CallBack<BaseBean> {

        @Override
        public void onSuccess(BaseBean response, Context context, Object tag) {
            hideProgress();
            Utils.showToast(context, response.getMessage());
            if (response.getCode() == RESPONSE_CODE_SUC) {
                //删除商品成功之后将已选择商品集合清空并重新设置总值

                selectCartGoodsList.clear();
                alterTotalPrice(selectCartGoodsList);
                getCartGoodsData(context);
            }
        }

        @Override
        public void onFailure(String message) {
            mView.hideProgress();
        }
    }

}
